package com.student_system.students.controller;

import com.student_system.common.Result;
import com.student_system.dto.StudentCourseAssignDTO;
import com.student_system.students.entity.StudentCourse;
import com.student_system.students.service.IStudentCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ljy
 * @since 2025-05-14
 */
@RestController
@RequestMapping("/studentCourse")
public class StudentCourseController {

    @Autowired
    private IStudentCourseService studentCourseService;

    //根据学生编号获取(查询)已分配给学生的课程编号
    @GetMapping("/getByStudentNo")
    public Result.ResultData<List<Integer>> getByStudentNo(@RequestParam Integer studentNo) {
        List<Integer> courseNos = studentCourseService.getCourseNosByStudentNo(studentNo);
        return Result.success(courseNos);
    }


    //将分配给学生的课程保存到中间表中
    @PostMapping("/assignCourses")
    public Result.ResultData<Void> assignCourses(@RequestBody StudentCourseAssignDTO dto){
        studentCourseService.assignCoursesToStudent(dto.getStudentNo(), dto.getCourseNos());
        return Result.success();
    }

    @PostMapping("/addGrade")
    public String addGrade(@RequestBody StudentCourse studentCourse) {
        return studentCourseService.saveOrUpdateGrade(
                studentCourse.getStudentNo(),
                studentCourse.getCourseNo(),
                studentCourse.getGrade()
        );
    }

    @GetMapping("/getGradesByStudentNo")
    public Result.ResultData<List<Map<String, Object>>> getGradesByStudentNo(
            @RequestParam Integer studentNo) {
        try {
            List<Map<String, Object>> grades = studentCourseService.getGradesByStudentNo(studentNo);
            if (grades == null || grades.isEmpty()) {
                return Result.error("404", "未找到该学生的成绩记录");
            }
            return Result.success(grades);
        } catch (Exception e) {
            return Result.error("500", "获取成绩失败: " + e.getMessage());
        }
    }
}